<?php
declare (strict_types = 1);

namespace app\im\service;

use think\swoole\Websocket;

class Message
{
    protected $type;
    protected $message;
    public function __construct($type,$message)
    {
        $this->type = $type;
        $this->message = $message;
    }
    public static function make($type='success', array|string $message = ''): array
    {
        $instance = new self($type, $message);
        return $instance->toArray();
    }
    public function toArray(): array
    {
        return [
            'msg_type' => $this->type,
            'message' => $this->message,
        ];
    }

}
class Chat
{
    protected Websocket $ws;
    protected int $appid;
    public function __construct(Websocket $websocket,$appid)
    {
        $this->ws = $websocket;
        $this->appid = $appid;
    }

    /**
     * 绑定用户
     * @param $user_id
     * @return void
     */
    public function bindUser($user_id): void
    {
        $this->ws->join($this->appid.'_loginBind');
        $this->ws->join($user_id);
        $this->ws->to((string)$user_id)->emit('success', ...(Message::make('bind', '登录成功')));
    }
    //刷新token
    public function refreshToken($user_id,$data): void
    {
        $this->ws->to((string)$user_id)->emit('success', ...(Message::make('refreshToken', $data)));
    }
    //发送Ping心跳
    public function sendPing(): void
    {
        $this->ws->emit('ping', ...(Message::make('ping', (string)time())));
    }
    //错误消息
    public function error($msg_type,$msg): void
    {
        $this->ws->emit('error', ...(Message::make($msg_type, $msg)));
    }
}
